import string
import random
from datetime import datetime
from typing import Optional

# 全局计数器,用于生成顺序ID
_student_counter = 50  # 从51开始,因为已有50名学生
_teacher_counter = 15  # 从16开始,因为已有15名教师
_admin_counter = 5     # 从6开始,因为已有5名管理员
_course_counter = 25   # 从26开始,因为已有25门课程

def generate_id(prefix: str = "USER_") -> str:
    """生成唯一ID:前缀+8位随机字符(排除易混淆字符O、0、I、1)
    
    如果prefix是"STU_",则使用顺序编号格式STU_001, STU_002等
    其他前缀保持原有的随机字符生成逻辑
    """
    import random
    import string
    
    # 如果是学生ID,使用顺序编号
    if prefix == "STU_":
        # 从data.json中查找最大的学生编号
        try:
            import json
            import os
            
            data_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data.json")
            if os.path.exists(data_file):
                with open(data_file, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    # 查找现有的学生ID
                    student_ids = []
                    for user in data.get("users", []):
                        if "student_id" in user and user["student_id"].startswith("STU_"):
                            try:
                                # 提取数字部分
                                num_part = user["student_id"][4:]
                                if num_part.isdigit():
                                    student_ids.append(int(num_part))
                            except ValueError:
                                continue
                    
                    if student_ids:
                        next_id = max(student_ids) + 1
                    else:
                        next_id = 1
                    
                    return f"STU_{next_id:03d}"
        except Exception:
            # 如果读取失败,从1开始
            next_id = 1
            return f"STU_{next_id:03d}"
    
    # 其他前缀保持原有逻辑
    characters = string.ascii_uppercase + string.digits
    # 排除易混淆字符
    characters = characters.replace('O', '').replace('0', '').replace('I', '').replace('1', '')
    
    random_part = ''.join(random.choice(characters) for _ in range(8))
    return prefix + random_part


def input_validation(input_value: str, input_type: str) -> bool:
    """输入验证工具"""
    if not isinstance(input_value, str) or len(input_value.strip()) == 0:
        return False
    
    input_value = input_value.strip()
    if input_type == "username":
        return 3 <= len(input_value) <= 15 and input_value[0].isalpha() and input_value.isalnum()
    elif input_type == "password":
        has_upper = any(c.isupper() for c in input_value)
        has_lower = any(c.islower() for c in input_value)
        has_digit = any(c.isdigit() for c in input_value)
        return 6 <= len(input_value) <= 20 and has_upper and has_lower and has_digit
    elif input_type == "email":
        if "@" not in input_value or "." not in input_value:
            return False
        at_index = input_value.index("@")
        dot_index = input_value.rindex(".")
        return at_index < dot_index and at_index > 0 and dot_index < len(input_value) - 1
    else:
        return False

def error_handling(exception: Exception) -> None:
    """统一错误处理"""
    print(f"Error: {exception}")
    # 这里可以添加日志记录功能

def format_date(date_str: str, target_format: str = "%Y-%m-%d") -> str:
    """日期格式化"""
    try:
        date_obj = datetime.strptime(date_str, "%Y-%m-%d")
        return date_obj.strftime(target_format)
    except ValueError:
        return date_str
    
def input_choice(prompt: str, max_choice: int) -> Optional[int]:
    """获取用户选择并验证
    
    Args:
        prompt: 提示信息
        max_choice: 最大可选数字
        
    Returns:
        int: 有效的选择数字,如果输入无效则返回None
    """
    try:
        choice = input(prompt).strip()
        if not choice.isdigit():
            print("❌ Please enter a valid number.")
            return None
        
        choice_num = int(choice)
        if 1 <= choice_num <= max_choice:
            return choice_num
        else:
            print(f"❌ Please enter a number between 1 and {max_choice}.")
            return None
    except Exception as e:
        print(f"❌ Error: {e}")
        return None
    
def input_positive_integer(prompt: str, default: int = None) -> int:
    """获取正整数输入,支持默认值
    
    Args:
        prompt: 提示信息
        default: 默认值,如果用户直接回车则使用
    
    Returns:
        int: 有效的正整数输入
    """
    while True:
        try:
            user_input = input(prompt).strip()
            if not user_input and default is not None:
                return default
            value = int(user_input)
            if value > 0:
                return value
            else:
                print("❌ Please enter a positive integer.")
        except ValueError:
            print("❌ Invalid input. Please enter a number.")
